import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { Card, Row, Col, Input, Button, Table, Space, message, Pagination, Modal } from 'antd'
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { getGoodsList, deleteGoodsAPI } from '../../app/goods'
import dayjs from 'dayjs'
import './index.less'

const { Search } = Input
const { confirm } = Modal
export default function Goods () {
    // 初始化查询信息
    const [ queryInfo, setQueryInfo ] = useState({query: '', pagenum: 1, pagesize: 2})
    // 初始化列表数据
    const [goodsList, setGoodsList] = useState([])
    // 初始化分页总数量
    const [goodsTotal, setGoodsTotal] = useState(0)

    // 获取商品列表
    const loadGoodsList = async () => {
        const { data, meta } = await getGoodsList(queryInfo)
        if(meta.status !== 200) return message.error('获取商品列表失败')
        const {total, goods} = data
        goods.forEach((item, index) => item.index = index)
        message.success('获取商品列表成功')
        setGoodsList(goods)
        setGoodsTotal(total)
    }
    // 监听queryInfo改变
    useEffect(() => {
        loadGoodsList()
    }, [queryInfo])

    // 搜索，获取数据
    const onSearch = query => setQueryInfo(e => ({...e, query}))
    // 鼠标按下触发搜索
    const onKeyDownSearch = e => onSearch(e.target.value)

    // 删除商品
    const deleteGoods = id => {
        confirm({
            title: '该操作将永久删除此商品',
            icon: <ExclamationCircleOutlined />,
            content: '请确认',
            okText: '确认',
            cancelText: '取消',
            async onOk() {
                const { meta } = await deleteGoodsAPI(id)
                if(meta.status !== 200) return message.error('删除该商品失败')
                message.success('删除该商品成功')
                if(goodsList.length === 1) {
                    setQueryInfo(e => ({...e, pagenum: e.pagenum === 1 ? 1 : (e.pagenum-1)}))
                }
            }
          })
    }

    // 分页改变
    const paginationChange = (pagenum, pagesize) => setQueryInfo(e => ({...e, pagenum, pagesize}))

    // 添加商品
    const addGoods = () => {}
    // 编辑商品
    const editGoods = () => {}

     // 表格每一列标题
     const columns = [
        {
          title: '#',
          dataIndex: 'index',
          width:'50px'
        },
        {
          title: '商品名称',
          dataIndex: 'goods_name',
          key:'goods_name'
        },
        {
          title: '商品价格（元）',
          dataIndex: 'goods_price',
          key:'goods_price',
          width:'150px'
        },
        {
          title: '商品重量',
          dataIndex: 'goods_weight',
          key:'goods_weight',
          width:'150px'
        },
        {
          title: '创建时间',
          dataIndex: 'add_time',
          key:'add_time',
          width:'200px',
          render: text => {
            return dayjs(text * 1000).format('YYYY-MM-DD')
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key:'operation',
          width:'150px',
          render:(_, record) => {
            const component = <>
            <Space>
              <Button key="1" type="primary" onClick={() => editGoods(record)} icon={<EditOutlined />}>
              </Button>
              <Button key="2" type="danger" onClick={() => deleteGoods(record.goods_id)} icon={<DeleteOutlined />}>
              </Button>
            </Space>
            </>
            return component
          }
        }
      ]
    return (
        <Card className="goods-container">
            {/* 搜索 */}
            <Row>
                <Col span={12}>
                    <Search onPressEnter={onKeyDownSearch} onSearch={onSearch} placeholder="请输入内容" />
                </Col>
                <Col span={4}>
                    <Link to="/goods/add">
                    <Button onClick={addGoods} type="primary" className="add-goods-btn">添加商品</Button>
                    </Link>
                </Col>
            </Row>
            {/* 商品列表 table 表格 */}
            <Table
                bordered
                columns={columns}
                dataSource={goodsList}
                pagination={false}
                rowKey={record => record.goods_id}
            />
            {/* 分页 */}
            <Pagination
                total={goodsTotal}
                showTotal={total => `总共 ${total} 条`}
                defaultPageSize={queryInfo.pagesize}
                current={queryInfo.pagenum}
                pageSizeOptions={[2,4,8,10]}
                onChange={paginationChange}
                showSizeChanger
            />
        </Card>
    )
}